﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common.Extends;
using XKPlatform.DataModels;
using XKPlatform.Common;
using XKPlatform.DataModels.ParamsModel;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.Common.Enums;
using XKPlatform.DataModels.Dao.BaseDao;

namespace XKPlatform.Controllers
{
    [Route("[controller]/[action]")]
    public class ApiController : Controller
    { 

        public ApiController()
        { 
        }
        public JsonResult getFormDataList(Search search, Guid? FormID)
        {
            if (!FormID.HasValue)
                return Json(new { code = 1, msg = "非法操作" });

            QuerySuite querySuite = new QuerySuite("SysForm", "FormNo");
            querySuite.AddParam("FormID", "=", FormID);

            var table = SqlHelper.GetSingle(querySuite.SelectSql, querySuite.Params);
            if (table == null && string.IsNullOrEmpty(table.ToString()))
                return Json(new { code = 1, msg = "非法操作" });

            var tableName = table.ToString();

            querySuite = new QuerySuite(tableName + " a left join SysProjectApi b on a.ID=b.ApiId left join SysProject d on b.ProId=d.No where a.RecordStatus=0", "a.*,d.ProjectName as ProId", search);

            DataSet ds = SqlHelper.Query(querySuite.LimitSql, querySuite.Params);

            return Json(new { code = 0, data = QuerySuite.ToDictionary(ds.Tables[0]), count = QuerySuite.DsCount(ds) });

        }

        /// <summary>
        /// 获取按钮和列按钮配置
        /// </summary>
        /// <param name="sysApiParams"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetButtonPageList([FromBody] SysApiParams sysApiParams)
        {
            // 默认筛选按钮和列按钮
            string where = " and (description = '1' or description = '2') ";

            if (sysApiParams.ApiNames.IsNotNullOrEmpty())
            {
                where += $" and ApiName like '%{sysApiParams.ApiNames}%'";
            }

            if (sysApiParams.interfaces.IsNotNullOrEmpty())
            {
                where += $" and interface like '%{sysApiParams.interfaces}%'";
            }

            List<sysApiModel> sysApiModels = _IsysApiService.GetList(sysApiParams.Page, sysApiParams.Limit, where, null, "ModifiedOn", 2, out int totalCount);

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = sysApiModels, count = totalCount });
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sysApiModels"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddApi([FromBody] List<sysApiModel> sysApiModels)
        {
            foreach (var item in sysApiModels)
            {
                item.ID = Guid.NewGuid().ToString();
                item.ModifiedBy = SSOClient.getUser(HttpContext).UserID.ToString();
                item.ModifiedOn = DateTime.Now;
            }

            BaseFreeSqlDao<sysApiModel> baseFreeSqlDao = new BaseFreeSqlDao<sysApiModel>();

            baseFreeSqlDao.BatchInsert(sysApiModels);

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Delete(string id)
        {
            _IsysApiService.Delete($" and ID = '{id}' ", null);
            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Get(string id)
        {
            sysApiModel sysApiModel = _IsysApiService.GetModel($" and ID = '{id}' ", new Dictionary<string, object>());

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = sysApiModel });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sysApiModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Edit([FromForm] sysApiModel sysApiModel)
        {
            _IsysApiService.Update(sysApiModel, $" and ID = '{sysApiModel.ID}'");
            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
        }

        #region 新增
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sysApiModel"></param>
        /// <param name="_formId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Save(sysApiModel sysApiModel, Guid? _formId)
        {
            if (!_formId.HasValue)
                return Json(new { code = 1, msg = "表单不存在！" });

            // 新增
            if (sysApiModel.ID.IsNullOrEmpty())
            {
                int count = _IsysApiService.Insert(sysApiModel);

                return Json(new { code = count > 0 ? 0 : 1, updateData = sysApiModel });
            }
            // 编辑 
            _IsysApiService.Update(sysApiModel, $" and Id='{sysApiModel.ID}'");

            return Json(new { code = 0, updateData = sysApiModel });


        }

        #endregion
    }
}